from django.shortcuts import render, redirect
from django.shortcuts import HttpResponse

from django.contrib.auth.models import User
from django.contrib.auth import authenticate  # 认证
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required


# Create your views here.

def index(request):
    # user = request.user
    return render(request, 'aiindex.html')


@login_required
def needlogin(request):
    return HttpResponse("这是一个需要登录才能看到的界面")


def register(request):
    if request.method == "GET":
        return render(request, 'register.html')
    if request.method == "POST":
        name = request.POST.get("name", "")
        password = request.POST.get("password", "")
        email = request.POST.get("email", "")
        # 注册到数据库
        # User.objects.create_superuser(username=name, password=password)
        User.objects.create_user(username=name, password=password, email=email)

        return redirect('ai2109:index')


def loginx(request):
    if request.method == "GET":
        return render(request, 'login1.html')
    if request.method == "POST":
        name = request.POST.get("name", "")
        password = request.POST.get("password", "")
        # 进行认证  --> 和后台数据库数据进行比对
        # print(name)
        # print(password)
        # user = authenticate(username=name, password=password)

        authentication = CustomBackend()
        user = authentication.authenticate(username=name, password=password)
        # print(user)
        if user is not None:
            print(user.username)
            # login(request, user=user)
            login(request, user, backend='django.contrib.auth.backends.ModelBackend')
            return redirect("ai2109:index")
        return redirect('ai2109:register')


def logoutx(request):
    logout(request)
    return redirect("ai2109:index")


from django.contrib.auth.backends import ModelBackend
from django.db.models import Q


class CustomBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            print(username, password)
            user = User.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            print(e)
            return None
